<template>
  <div>
    <el-dialog v-model="dialogVisible" title="密码修改" @close="handleClose" width="30%">
      <el-form ref="formRef" :model="formData" :rules="formRules" label-width="100px" label-position="left">
        <el-form-item prop="password" label="密码">
          <el-input type="password" v-model="formData.password" placeholder="请输入" />
        </el-form-item>
        <el-form-item prop="new_password" label="新密码">
          <el-input type="password" v-model="formData.new_password" placeholder="请输入" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="handleCreate">确认</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { reactive, ref } from "vue"
import { ElMessage, FormInstance, FormRules } from "element-plus"
import { adminEditPasswordApi } from "@/api/system"

const dialogVisible = ref<boolean>(false)
const formRef = ref<FormInstance | null>(null)
const ids = ref("")
const formData = reactive({
  password: "",
  new_password: ""
})
const formRules: FormRules = reactive({
  password: [{ required: true, trigger: "blur", message: "请输入密码" }],
  new_password: [{ required: true, trigger: "blur", message: "请输入新密码" }]
})
const emit = defineEmits(["DialogClose"])
const handleCreate = () => {
  formRef.value?.validate((valid: boolean, fields) => {
    if (valid) {
      console.log(formData)
      adminEditPasswordApi({
        id: ids.value,
        password: formData.password,
        new_password: formData.new_password
      })
        .then(() => {
          ElMessage.success("修改成功")
        })
        .finally(() => {
          handleClose()
        })
    } else {
      console.error("表单校验不通过", fields)
    }
  })
}

const handleUpdate = async (row: any | undefined) => {
  dialogVisible.value = true
  ids.value = row.id
  console.log(ids)
  console.log(row)
}
const handleClose = async () => {
  formRef.value?.resetFields()
  resetForm()
  dialogVisible.value = false
  emit("DialogClose", true)
}

const resetForm = () => {
  formData.password = ""
  formData.new_password = ""
}
defineExpose({ handleUpdate })
</script>

<style scoped lang="scss"></style>
